<template>
  <div class="userLoginView">
    <h2>用户登录</h2>
    <a-form
      style="max-width: 360px; margin: 0 auto"
      :model="form"
      auto-label-width
      label-align="left"
      @submit="handleSubmit"
      :size="size"
    >
      <a-form-item field="userAccount" label="账号">
        <a-input v-model="form.userAccount" placeholder="请输入账号" />
      </a-form-item>
      <a-form-item field="userPassword" label="密码">
        <a-input-password
          v-model="form.userPassword"
          tooltip="密码不少于8位"
          placeholder="please enter your post..."
        />
      </a-form-item>
      <a-form-item>
        <a-button
          html-type="submit"
          type="primary"
          style="width: 120px; margin: 0 auto"
          >登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { UserControllerService, UserLoginRequest } from "../../../api";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

/**
 * 表单信息
 */
const form = reactive({
  userAccount: "",
  userPassword: "",
} as UserLoginRequest);

const router = useRouter();
const store = useStore();
const size = "large";

/**
 * 提交表单
 * @param data
 */
const handleSubmit = async () => {
  const response = await UserControllerService.userLoginUsingPost(form);
  //登录成功,跳转到首页 todo 后续修改成跳转到登录前的redirect请求页面
  if (response.code === 0) {
    //两种方法设置用户登录信息方法
    // 1.使用setLoginUser会根据返回的数据设置登录用户信息
    // await store.dispatch("user/setLoginUser", response.data);
    // 2.使用getLoginUser,请求后端获取登陆的用户信息,但是这种方法要在openapi.ts中设置携带凭证(即cookie)选项为true,否则无法获取用户信息
    message.success("登录成功");
    await store.dispatch("user/getLoginUser");
    router.push({
      path: "/",
      replace: true,
    });
    console.log(response);
    console.log(store.state.user.loginUser);
    /*    const route = useRoute();
        const redirect = route.query.redirect as string | undefined;
        if (redirect) {
          const router = useRouter();
          await router.push(redirect);
          return;
        }*/
  } else {
    message.error("登陆失败" + response.message);
  }
};
</script>
<style>
.userLoginView {
  width: 600px;
  background: white;
  margin: 100px auto;
  padding: 20px;
  border-radius: 10px;
}
</style>
